<?php

namespace App\Models;

use Dcat\Admin\Traits\HasDateTimeFormatter;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;

/**
 * App\Models\ServiceCategory
 *
 * @property int $id
 * @property string $name 名称
 * @property int $sort 排序
 * @property int $status 状态:0=正常,1=隐藏
 * @property \Illuminate\Support\Carbon|null $created_at
 * @property \Illuminate\Support\Carbon|null $updated_at
 * @method static \Illuminate\Database\Eloquent\Builder|ServiceCategory newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|ServiceCategory newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|ServiceCategory query()
 * @method static \Illuminate\Database\Eloquent\Builder|ServiceCategory whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|ServiceCategory whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|ServiceCategory whereName($value)
 * @method static \Illuminate\Database\Eloquent\Builder|ServiceCategory whereSort($value)
 * @method static \Illuminate\Database\Eloquent\Builder|ServiceCategory whereStatus($value)
 * @method static \Illuminate\Database\Eloquent\Builder|ServiceCategory whereUpdatedAt($value)
 * @mixin \Eloquent
 */
class ServiceCategory extends Model
{
	use HasDateTimeFormatter;
    protected $table = 'service_category';

    protected static function booted()
    {
        self::deleting(function (ServiceCategory $category){
            $exit = Service::query()->where("cid",$category->id)->exists();
            if ($exit){
                modelError("此分类关联服务项目,不可删除!");
            }
            self::deleting(function (ServiceCategory $category){
                $exit = Coupon::query()->where("cid",$category->id)->exists();
                if ($exit){
                    modelError("此分类关联优惠券信息,不可删除!");
                }
            });
        });
    }


    public static function getOptions($shop_id = 0): Collection
    {
        return self::query()->when($shop_id,function ($query,$value){
            $query->where("shop_id",$value);
        })->orderByDesc("sort")->orderByDesc("id")->pluck("name","id");
    }

    public static function getList($shop_id = 0): Collection|array
    {
        return self::query()->when($shop_id,function ($query,$value){
            $query->where("shop_id",$value);
        })->where("status",0)
            ->orderByDesc("sort")
            ->orderByDesc("id")->get(['id','name']);
    }



}
